import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/member.dart';
import '../widgets/member_list.dart';
import '../widgets/add_member_dialog.dart';
import '../providers/auth_provider.dart';
import '../providers/member_provider.dart';
import './member_screen.dart';
import '../widgets/add_task_dialog.dart';
import '../widgets/task_list.dart';
import '../providers/task_provider.dart';
import '../services/notification_service.dart';
import './analytics_screen.dart';
import '../providers/theme_provider.dart';
import '../providers/member_filter_provider.dart';
import '../widgets/custom_window_frame.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  late TextEditingController _emailController;
  late TextEditingController _passwordController;
  final _formKey = GlobalKey<FormState>();
  bool _showCompleted = false;
  final TextEditingController _searchController = TextEditingController();
  String _searchQuery = '';
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final NotificationService _notifications = NotificationService();

  @override
  void initState() {
    super.initState();
    _emailController = TextEditingController();
    _passwordController = TextEditingController();
  }

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    _searchController.dispose();
    super.dispose();
  }

  void _showLoginDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: const Text('用户登录'),
        content: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextFormField(
                controller: _emailController,
                decoration: const InputDecoration(
                  labelText: '用户名',
                  icon: Icon(Icons.person),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入用户名';
                  }
                  return null;
                },
              ),
              TextFormField(
                controller: _passwordController,
                decoration: const InputDecoration(
                  labelText: '密码',
                  icon: Icon(Icons.lock),
                ),
                obscureText: true,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入密码';
                  }
                  return null;
                },
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () {
              _emailController.clear();
              _passwordController.clear();
              Navigator.pop(context);
            },
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                final memberProvider = Provider.of<MemberProvider>(context, listen: false);
                final authProvider = Provider.of<AuthProvider>(context, listen: false);

                memberProvider.getMemberByName(_emailController.text).then((member) {
                  if (member != null && member.password == _passwordController.text) {
                    authProvider.setCurrentUser(member);
                    _emailController.clear();
                    _passwordController.clear();
                    Navigator.pop(context);  // 关闭登录对话框
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(builder: (context) => const HomeScreen()),
                    );
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('欢迎回来，${member.name}')),
                    );
                  } else {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: Text('登录失败：账号或密码错误')),
                    );
                  }
                });
              }
            },
            child: const Text('登录'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return CustomWindowFrame(
      child: Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          leading: IconButton(
            icon: const Icon(Icons.menu),
            onPressed: () {
              _scaffoldKey.currentState?.openDrawer();
            },
          ),
          title: TextField(
            controller: _searchController,
            decoration: InputDecoration(
              hintText: '搜索任务...',
              border: InputBorder.none,
              enabledBorder: InputBorder.none,
              focusedBorder: InputBorder.none,
              prefixIcon: const Icon(Icons.search),
              suffixIcon: _searchQuery.isNotEmpty
                  ? IconButton(
                      icon: const Icon(Icons.clear),
                      onPressed: () {
                        setState(() {
                          _searchController.clear();
                          _searchQuery = '';
                        });
                      },
                    )
                  : null,
            ),
            onChanged: (value) {
              setState(() {
                _searchQuery = value;
              });
            },
          ),
          backgroundColor: Theme.of(context).colorScheme.inversePrimary,
          actions: const [],
        ),
        drawer: Consumer<AuthProvider>(
          builder: (context, authProvider, child) {
            final bool isAdmin = authProvider.isAdmin;
            final bool isGuest = authProvider.isGuest;

            return Drawer(
              shape: const RoundedRectangleBorder(
                borderRadius: BorderRadius.only(
                  topRight: Radius.circular(3),
                  bottomRight: Radius.circular(3),
                ),
              ),
              child: ListView(
                padding: EdgeInsets.zero,
                children: [
                  DrawerHeader(
                    decoration: BoxDecoration(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          '待到山花烂漫时，她在丛中笑。',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 24,
                          ),
                        ),
                        const SizedBox(height: 16),
                        Text(
                          isGuest 
                              ? '当前以访客身份使用'
                              : '欢迎，${authProvider.currentUser!.name}',
                          style: const TextStyle(color: Colors.white70),
                        ),
                      ],
                    ),
                  ),
                  ListTile(
                    leading: const Icon(Icons.list),
                    title: const Text('所有任务'),
                    onTap: () {
                      setState(() => _showCompleted = false);
                      Navigator.pop(context);
                    },
                  ),
                  if (!isGuest) ...[  // 非访客才显示这些选项
                    ListTile(
                      leading: const Icon(Icons.done_all),
                      title: const Text('已完成任务'),
                      onTap: () {
                        setState(() => _showCompleted = true);
                        Navigator.pop(context);
                      },
                    ),
                    if (isAdmin)  // 只有管理员可以看到这些选项
                      ListTile(
                        leading: const Icon(Icons.people),
                        title: const Text('成员管理'),
                        onTap: () {
                          Navigator.pop(context);
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => const MemberScreen(),
                            ),
                          );
                        },
                      ),
                  ],
                  ListTile(
                    leading: const Icon(Icons.admin_panel_settings),
                    title: Text(
                      context.watch<AuthProvider>().currentUser == null 
                        ? '登录管理员' 
                        : '退出登录 (${context.watch<AuthProvider>().currentUser?.name})'
                    ),
                    onTap: () {
                      final authProvider = context.read<AuthProvider>();
                      if (authProvider.currentUser == null) {
                        Navigator.pop(context);  // 先关闭抽屉
                        _showLoginDialog(context);  // 显示登录对话框
                      } else {
                        authProvider.logout();
                        Navigator.pop(context);  // 关闭抽屉
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('已退出登录')),
                        );
                      }
                    },
                  ),
                  ListTile(
                    leading: const Icon(Icons.notifications_active),
                    title: const Text('提醒设置'),
                    enabled: _notifications.isSupported,
                    onTap: () {
                      if (!_notifications.isSupported) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('当前平台不支持通知功能')),
                        );
                        return;
                      }
                      Navigator.pop(context);  // ��闭抽屉
                      showDialog(
                        context: context,
                        builder: (context) => AlertDialog(
                          title: const Text('提醒设置'),
                          content: Consumer<TaskProvider>(
                            builder: (context, taskProvider, child) {
                              final pendingTasks = taskProvider.pendingTasks
                                  .where((task) => task.dueDate != null)
                                  .toList();
                              
                              if (pendingTasks.isEmpty) {
                                return const Text('没有待办任务需要设置提醒');
                              }

                              return SizedBox(
                                width: double.maxFinite,
                                child: SingleChildScrollView(
                                  child: Column(
                                    mainAxisSize: MainAxisSize.min,
                                    children: pendingTasks.map((task) {
                                      return ListTile(
                                        title: Text(
                                          task.title,
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                        subtitle: Text(
                                          '截止时间: ${task.dueDate?.toString().split('.')[0] ?? '无'}',
                                        ),
                                        trailing: Row(
                                          mainAxisSize: MainAxisSize.min,
                                          children: [
                                            IconButton(
                                              icon: const Icon(Icons.alarm_add),
                                              tooltip: '设置提醒',
                                              onPressed: () {
                                                _notifications.scheduleTaskReminder(task);
                                                ScaffoldMessenger.of(context).showSnackBar(
                                                  SnackBar(
                                                    content: Text('已为任务"${task.title}"设置提醒'),
                                                  ),
                                                );
                                              },
                                            ),
                                            IconButton(
                                              icon: const Icon(Icons.alarm_off),
                                              tooltip: '取消提醒',
                                              onPressed: () {
                                                _notifications.cancelTaskReminder(task);
                                                ScaffoldMessenger.of(context).showSnackBar(
                                                  SnackBar(
                                                    content: Text('已取消任务"${task.title}"的提醒'),
                                                  ),
                                                );
                                              },
                                            ),
                                          ],
                                        ),
                                      );
                                    }).toList(),
                                  ),
                                ),
                              );
                            },
                          ),
                          actions: [
                            TextButton(
                              onPressed: () {
                                _notifications.cancelAllReminders();
                                Navigator.pop(context);
                                ScaffoldMessenger.of(context).showSnackBar(
                                  const SnackBar(
                                    content: Text('已取消所有提醒'),
                                  ),
                                );
                              },
                              child: const Text('取消所有提醒'),
                            ),
                            TextButton(
                              onPressed: () => Navigator.pop(context),
                              child: const Text('关闭'),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                  ListTile(
                    leading: const Icon(Icons.analytics),
                    title: const Text('统计分析'),
                    onTap: () {
                      Navigator.pop(context);  // 关闭抽屉
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => const AnalyticsScreen(),
                        ),
                      );
                    },
                  ),
                  ListTile(
                    leading: const Icon(Icons.palette),
                    title: const Text('主题设置'),
                    onTap: () {
                      Navigator.pop(context);  // 关闭抽屉
                      showDialog(
                        context: context,
                        builder: (context) => Dialog(
                          child: ConstrainedBox(
                            constraints: const BoxConstraints(
                              maxWidth: 400,
                              maxHeight: 600,
                            ),
                            child: Padding(
                              padding: const EdgeInsets.all(20),
                              child: SingleChildScrollView(
                                child: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        const Text(
                                          '主题设置',
                                          style: TextStyle(
                                            fontSize: 20,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                        IconButton(
                                          icon: const Icon(Icons.close),
                                          onPressed: () => Navigator.pop(context),
                                        ),
                                      ],
                                    ),
                                    const SizedBox(height: 20),
                                    const Text(
                                      '选择主题颜色',
                                      style: TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    const SizedBox(height: 16),
                                    GridView.builder(
                                      shrinkWrap: true,
                                      physics: const NeverScrollableScrollPhysics(),
                                      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                                        crossAxisCount: 4,
                                        mainAxisSpacing: 12,
                                        crossAxisSpacing: 12,
                                        childAspectRatio: 1,
                                      ),
                                      itemCount: ThemeProvider.themeColors.length,
                                      itemBuilder: (context, index) {
                                        final color = ThemeProvider.themeColors[index];
                                        final isSelected = color == context.watch<ThemeProvider>().currentColor;
                                        final isDark = color == const Color(0xFF23292E);
                                        
                                        return Material(
                                          child: InkWell(
                                            onTap: () {
                                              context.read<ThemeProvider>().updateThemeColor(color);
                                            },
                                            borderRadius: BorderRadius.circular(50),
                                            child: AnimatedContainer(
                                              duration: const Duration(milliseconds: 200),
                                              decoration: BoxDecoration(
                                                color: color,
                                                shape: BoxShape.circle,
                                                border: Border.all(
                                                  color: isSelected 
                                                      ? Theme.of(context).colorScheme.primary
                                                      : Colors.grey.withOpacity(0.3),
                                                  width: isSelected ? 3 : 1,
                                                ),
                                                boxShadow: isSelected
                                                    ? [
                                                        BoxShadow(
                                                          color: color.withOpacity(0.4),
                                                          blurRadius: 8,
                                                          spreadRadius: 2,
                                                        )
                                                      ]
                                                    : null,
                                              ),
                                              child: isSelected
                                                  ? Icon(
                                                      Icons.check,
                                                      color: isDark || color == const Color(0xFFFAFAFA)
                                                          ? Colors.white.withOpacity(0.9)
                                                          : Colors.white,
                                                      size: 28,
                                                    )
                                                  : null,
                                            ),
                                          ),
                                        );
                                      },
                                    ),
                                    const SizedBox(height: 24),
                                    const Text(
                                      '主题模式',
                                      style: TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    const SizedBox(height: 16),
                                    Consumer<ThemeProvider>(
                                      builder: (context, themeProvider, child) {
                                        return SegmentedButton<ThemeMode>(
                                          segments: const [
                                            ButtonSegment(
                                              value: ThemeMode.system,
                                              label: Text('跟随系统'),
                                              icon: Icon(Icons.brightness_auto),
                                            ),
                                            ButtonSegment(
                                              value: ThemeMode.light,
                                              label: Text('浅色'),
                                              icon: Icon(Icons.brightness_high),
                                            ),
                                            ButtonSegment(
                                              value: ThemeMode.dark,
                                              label: Text('深色'),
                                              icon: Icon(Icons.brightness_4),
                                            ),
                                          ],
                                          selected: {themeProvider.themeMode},
                                          onSelectionChanged: (Set<ThemeMode> modes) {
                                            themeProvider.updateThemeMode(modes.first);
                                          },
                                        );
                                      },
                                    ),
                                    const SizedBox(height: 24),
                                    const Text(
                                      '预览效果',
                                      style: TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    const SizedBox(height: 16),
                                    Consumer<ThemeProvider>(
                                      builder: (context, themeProvider, child) {
                                        final theme = themeProvider.getTheme();
                                        return Card(
                                          color: theme.colorScheme.surface,
                                          child: Padding(
                                            padding: const EdgeInsets.all(16),
                                            child: Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: [
                                                Row(
                                                  children: [
                                                    Icon(
                                                      Icons.palette,
                                                      color: theme.colorScheme.primary,
                                                    ),
                                                    const SizedBox(width: 8),
                                                    Text(
                                                      '主题预览',
                                                      style: TextStyle(
                                                        color: theme.colorScheme.onSurface,
                                                        fontWeight: FontWeight.bold,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                                const SizedBox(height: 16),
                                                Wrap(
                                                  spacing: 8,
                                                  runSpacing: 8,
                                                  children: [
                                                    ElevatedButton(
                                                      onPressed: () {},
                                                      child: const Text('按钮示例'),
                                                    ),
                                                    OutlinedButton(
                                                      onPressed: () {},
                                                      child: const Text('次要按钮'),
                                                    ),
                                                  ],
                                                ),
                                              ],
                                            ),
                                          ),
                                        );
                                      },
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ],
              ),
            );
          },
        ),
        body: TaskList(
          showCompleted: _showCompleted,
          searchQuery: _searchQuery,
        ),
        floatingActionButton: Consumer<TaskProvider>(
          builder: (context, taskProvider, child) {
            if (!taskProvider.canCreateTask(context)) return const SizedBox.shrink();
            
            return FloatingActionButton(
              onPressed: () {
                showDialog(
                  context: context,
                  builder: (context) => const AddTaskDialog(),
                );
              },
              child: const Icon(Icons.add),
            );
          },
        ),
      ),
    );
  }

  void _showAddMemberDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => const AddMemberDialog(),
    );
  }
} 